<?php
declare (strict_types = 1);

namespace app\api\controller;

use think\exception\ValidateException;

use app\common\model\{User, UserAddress, Apply, Order, FinancialRecord, Cash, Star};
use app\common\validate\{UserValidate, UserAddressValidate, ApplyValidate, OrderValidate, FinancialRecordValidate, CashValidate};

class UserController extends BaseController
{
    private $userModel;

    public function __construct(User $userModel)
    {
        parent::initialize();
        $this->userModel = $userModel;
    }

    /** 
     * 查询用户信息
     */
    public function getUserInfo()
    {
        $data = input('');

        try{
            validate(UserValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $orderModel = new Order();

        $orderWhere = [
            ['user_id', '=', $data['user_id']],
            ['status', 'in', [2,3,4]],
            ['create_time', '>', strtotime("-2 month")],
        ];

        /** 查询两个月内的订单信息 */
        $orderFlag = $orderModel->where($orderWhere)->find();

        /** 两个月内无进货，清空等级 */
        if(!$orderFlag){
            $this->userModel->edit(['id' => $data['user_id'], 'star' => 0, 'buy_number' => 0]);
        }

        $field = 'id, nickname, avatar, star, mobile, money, is_agent, create_time';
        $user_info = $this->userModel->getFind(['id' => $data['user_id']], $field);

        if($user_info['code'] != 'ok'){
            $this->error_back($user_info['msg']);
        }

        $this->success_back('ok', $user_info['data']);
    }

    /** 
     * 图片上传
     */
    public function imgUpload()
    {
        $img = request()->file('img');
        if(!$img) $this->error_back('上传图片为空');
        $this->success_back('ok', ['img_url' => fileUp($img, 'avatar')]);
    }

    /** 
     * 修改用户信息
     */
    public function setUserNews()
    {
        $data = input('');

        try{
            validate(UserValidate::class)->scene('set_user')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        if(isset($data['avatar']) && !empty($data['avatar'])){
            $data['avatar'] = $data['avatar'];
        }else{
            unset($data['avatar']);
        }

        $data['id'] = $data['user_id'];
        $edit_flag = $this->userModel->edit($data);

        if($edit_flag['code'] != 'ok'){
            $this->error_back($edit_flag['msg']);
        }

        $this->success_back('修改成功');
    }

    /**
     * 订单列表
     */
    public function getOrderList()
    {
        $data = input('');

        try{
            validate(OrderValidate::class)->scene('list_api')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $orderModel = new Order();

        $where = [
            ['o.user_id', '=', $data['user_id']],
            ['o.status', '=', $data['status']]
        ];

        $list = $orderModel->getOrderList($where);

        if($list->isEmpty()){
            $this->error_back('暂无数据');
        }

        $this->success_back('ok', $list);
    }

    /**
     * 确认收货
     */
    public function sendOrder()
    {
        $data = input('');

        try{
            validate(OrderValidate::class)->scene('send')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $orderModel = new Order();

        $orderInfo = $orderModel->getFind(['id' => $data['order_id']]);

        if($orderInfo['code'] != 'ok'){
            $this->error_back('订单不存在');
        }

        if($orderInfo['data']['status'] != 3){
            $this->error_back('订单状态错误');
        }

        $flag = $orderModel->edit(['id' => $data['order_id'], 'status' => 4, 'finish_time' => time()]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('收货成功');
    }

    /**
     * 删除订单
     */
    public function delOrder()
    {
        $data = input('');

        try{
            validate(OrderValidate::class)->scene('send')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $orderModel = new Order();

        $orderInfo = $orderModel->getFind(['id' => $data['order_id']]);

        if($orderInfo['code'] != 'ok'){
            $this->error_back('订单不存在');
        }

        if($orderInfo['data']['status'] != 4){
            $this->error_back('订单状态错误');
        }

        $flag = $orderModel::destroy($data['order_id']);

        if(!$flag){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }

    /** 
     * 新增收货地址
     */
    public function addAddress()
    {
        $data = input('');

        try{
            validate(UserAddressValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userAddressModel = new UserAddress();

        if($data['is_default']){
            $userAddressModel->editWhere(['is_default' => 0], ['user_id' => $data['user_id']]);
        }

        $flag = $userAddressModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('新增成功');
    }

    /** 
     * 编辑收货地址
     */
    public function setAddress()
    {
        $data = input('');

        try{
            validate(UserAddressValidate::class)->scene('set')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userAddressModel = new UserAddress();

        if($data['is_default']){
            $userAddressModel->editWhere(['is_default' => 0], ['user_id' => $data['user_id']]);
        }

        $flag = $userAddressModel->edit($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('编辑成功');
    }

    /** 
     * 获取收货地址列表
     */
    public function getAddressList()
    {
        $data = input('');

        try{
            validate(UserAddressValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userAddressModel = new UserAddress();

        $list = $userAddressModel->getList(['user_id' => $data['user_id']], 0, 0, 0, '*', 'is_default DESC, id DESC');

        if($list['code'] != 'ok'){
            $this->error_back($list['msg']);
        }

        $this->success_back('ok', $list['data']);
    }

    /** 
     * 删除收货地址
     */
    public function delAddress()
    {
        $data = input('');

        try{
            validate(UserAddressValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userAddressModel = new UserAddress();

        $flag = $userAddressModel->del(['id' => $data['address_id']]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }

    /** 
     * 设置默认地址
     */
    public function setDefault()
    {
        $data = input('');

        try{
            validate(UserAddressValidate::class)->scene('default')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userAddressModel = new UserAddress();

        $userAddressModel->editWhere(['is_default' => 0], ['user_id' => $data['user_id']]);

        $flag = $userAddressModel->edit(['id' => $data['address_id'], 'is_default' => 1]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('设置成功');
    }

    /**
     * 我的团队
     */
    public function getTeam()
    {
        $data = input('');

        try{
            validate(UserValidate::class)->scene('team')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where[] = ['pid', '=', $data['user_id']];

        $field = 'id, nickname, avatar, buy_number';
        $list = $this->userModel->getList($where, 0, $data['page'], $data['limit'], $field);

        if($list['code'] != 'ok'){
            $this->error_back($list['msg']);
        }

        $this->success_back('ok', $list['data']);
    }

    /** 
     * 申请代理
     */
    public function applyAgent()
    {
        $data = input('');

        try{
            validate(ApplyValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $applyModel = new Apply();

        /** 查询最后一条申请 */
        $info = $applyModel->getFind(['user_id' => $data['user_id']], '*', 'id DESC');

        if($info['code'] == 'ok' && $data['data']->getData('satus') != 3){
            $this->error_back('请勿重复提交');
        }

        $flag = $applyModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('提交申请成功');
    }

    /** 
     * 获取代理申请状态
     */
    public function getApplyStatus()
    {
        $data = input('');

        try{
            validate(ApplyValidate::class)->scene('show_api')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $applyModel = new Apply();

        /** 查询最后一条申请 */
        $info = $applyModel->getFind(['user_id' => $data['user_id']], '*', 'id DESC');

        if($info['code'] != 'ok'){
            $this->success_back('还未提交申请', ['status' => -1]);
        }

        $msg = '申请已通过';

        $backData = [
            'status'   => 2,
            'back_msg' => $info['data']['back_msg']
        ];

        switch ($info['data']->getData['status']) {
            case 1:
                $backData['status'] = 1;
                $msg = '申请已提交，请耐心等待审核。';
                break;
            case 3:
                $backData['status']  = 3;
                $msg = '申请已驳回，请重新提交申请。';
                break;
        }

        $this->success_back($msg, $backData);
    }

    /**
     * 我的钱包
     */
    public function getMoneyList()
    {
        $data = input('');

        try{
            validate(FinancialRecordValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $money = $this->userModel->getVal(['id' => $data['user_id']], 'money')['data'];

        $finModel = new FinancialRecord();

        $where[] = ['user_id', '=', $data['user_id']];

        $field = 'id, number, content, create_time';
        $list = $finModel->getList($where, 0, $data['page'], $data['limit'], $field);

        if($list['code'] != 'ok'){
            $this->error_back($list['msg']);
        }

        $this->success_back('ok', ['money' => $money, 'list' => $list['data']]);
    }

    /**
     * 提现
     */
    public function setCash()
    {
        $data = input('');

        try{
            validate(CashValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $cashModel = new Cash();

        $flag = $cashModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('已提交申请');
    }

    /**
     * 会员等级信息
     */
    public function getUserGrade()
    {
        $data = input('');

        try{
            validate(UserValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $field = 'id, star, buy_number';
        $userInfo = $this->userModel->getFind(['id' => $data['user_id']], $field);

        if($userInfo['code'] != 'ok'){
            $this->error_back($userInfo['msg']);
        }

        $starModel = new Star();

        $starInfo = $starModel->where([['id', '>', $userInfo['data']->getData('star')]])->find();

        if($starInfo){
            $backData = [
                'star'             => $userInfo['data']->getData('star'),
                'buy_number'       => $userInfo['data']['buy_number'],
                'up_grade_number'  => $starInfo['number'] - $userInfo['data']['buy_number'],
            ];
        }else{
            $backData = [
                'star'             => $userInfo['data']->getData('star'),
                'buy_number'       => -1,
                'up_grade_number'  => -1,
            ];
        }

        $this->success_back('ok', $backData);
    }

    /**
     * 获取小程序码
     */
    public function getCodeImg()
    {
        $data = input('');

        try{
            validate(UserValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $this->success_back('ok', ['code_img' => 'http://agent.shine.com//storage/banner/20210705/5752276b357c07efca51cffeeeec828e.png']);
    }
}